#include "config.h"
#include "VL53L0X.h"


#include	"STC32G_GPIO.h"
#include "STC32G_Soft_I2C.h"

#define VL53L0_address 0x52
#define decodeVcselPeriod(reg_val)      (((reg_val) + 1) << 1)
#define calcMacroPeriod(vcsel_period_pclks) ((((unsigned  long)2304 * (vcsel_period_pclks) * 1655) + 500) / 1000)

unsigned long measurement_timing_budget_us;

void VL53L0X_Write(unsigned char address, unsigned char value)
{
	SI2C_WriteNbyte(VL53L0_address,address,(u8*)&value,1);

}
void VL53L0X_Write16Bit(unsigned char address, unsigned int value)
{
	SI2C_WriteNbyte(VL53L0_address,address,(u8*)&value,2);
}
void VL53L0X_WriteMulti(unsigned char address, unsigned char const * src, unsigned char count)
{
	SI2C_WriteNbyte(VL53L0_address,address,src,count);
}


unsigned char VL53L0X_Read(unsigned char address)
{
	unsigned char p[1];
	SI2C_ReadNbyte(VL53L0_address,address,p,1);
	return p[0];
}
unsigned int VL53L0X_Read16Bit(unsigned char address)
{
  unsigned int receive;
  receive = VL53L0X_Read(address++) << 8;
	receive |= VL53L0X_Read(address);
  return receive;
}
void VL53L0X_ReadMulti(unsigned char address, unsigned char * dst, unsigned char count)
{
	SI2C_ReadNbyte(VL53L0_address,address,dst,count);
}
unsigned char stop_variable;

bit VL53L0X_setSignalRateLimit(float limit_Mcps)
{
  if (limit_Mcps < 0 || limit_Mcps > 511.99) { return 0; }

  // Q9.7 fixed point format (9 integer bits, 7 fractional bits)
  VL53L0X_Write16Bit(FINAL_RANGE_CONFIG_MIN_COUNT_RATE_RTN_LIMIT, limit_Mcps * (1 << 7));
  return 1;
}



void Delay100ms(void)	//@24.000MHz
{
	unsigned long edata i;

	_nop_();
	_nop_();
	i = 599998UL;
	while (i) i--;
}

// Private Methods /////////////////////////////////////////////////////////////

// Get reference SPAD (single photon avalanche diode) count and type
// based on VL53L0X_get_info_from_device(),
// but only gets reference SPAD count and type
bit VL53L0X_getSpadInfo(unsigned  char * count, unsigned char * type_is_aperture)
{
  unsigned  char tmp;

  VL53L0X_Write(0x80, 0x01);
  VL53L0X_Write(0xFF, 0x01);
  VL53L0X_Write(0x00, 0x00);

  VL53L0X_Write(0xFF, 0x06);
  VL53L0X_Write(0x83, VL53L0X_Read(0x83) | 0x04);
  VL53L0X_Write(0xFF, 0x07);
  VL53L0X_Write(0x81, 0x01);

  VL53L0X_Write(0x80, 0x01);

  VL53L0X_Write(0x94, 0x6b);
  VL53L0X_Write(0x83, 0x00);


  Delay100ms();
  if (VL53L0X_Read(0x83) == 0x00)
  {
	return 0;
  }
  
  VL53L0X_Write(0x83, 0x01);
  tmp = VL53L0X_Read(0x92);

  *count = tmp & 0x7f;
  *type_is_aperture = (tmp >> 7) & 0x01;

  VL53L0X_Write(0x81, 0x00);
  VL53L0X_Write(0xFF, 0x06);
  VL53L0X_Write(0x83, VL53L0X_Read( 0x83  & ~0x04));
  VL53L0X_Write(0xFF, 0x01);
  VL53L0X_Write(0x00, 0x01);

  VL53L0X_Write(0xFF, 0x00);
  VL53L0X_Write(0x80, 0x00);

  // The SPAD map (RefGoodSpadMap) is read by VL53L0X_get_info_from_device() in
  // the API, but the same data seems to be more easily readable from
  // GLOBAL_CONFIG_SPAD_ENABLES_REF_0 through _6, so read it from there



  return 1;
}


// Get sequence step enables
// based on VL53L0X_GetSequenceStepEnables()
void VL53L0X_getSequenceStepEnables(struct SequenceStepEnables * enables)
{
  unsigned  char sequence_config = VL53L0X_Read(SYSTEM_SEQUENCE_CONFIG);

  enables->tcc          = (sequence_config >> 4) & 0x1;
  enables->dss          = (sequence_config >> 3) & 0x1;
  enables->msrc         = (sequence_config >> 2) & 0x1;
  enables->pre_range    = (sequence_config >> 6) & 0x1;
  enables->final_range  = (sequence_config >> 7) & 0x1;
}
// Get the VCSEL pulse period in PCLKs for the given period type.
// based on VL53L0X_get_vcsel_pulse_period()
unsigned  char VL53L0X_getVcselPulsePeriod(enum vcselPeriodType type)
{
  if (type == VcselPeriodPreRange)
  {
    return decodeVcselPeriod(VL53L0X_Read(PRE_RANGE_CONFIG_VCSEL_PERIOD));
  }
  else if (type == VcselPeriodFinalRange)
  {
    return decodeVcselPeriod(VL53L0X_Read(FINAL_RANGE_CONFIG_VCSEL_PERIOD));
  }
  else { return 255; }
}
// Convert sequence step timeout from MCLKs to microseconds with given VCSEL period in PCLKs
// based on VL53L0X_calc_timeout_us()
unsigned  long VL53L0X_timeoutMclksToMicroseconds(unsigned  int timeout_period_mclks, unsigned  char vcsel_period_pclks)
{
  unsigned  long macro_period_ns = calcMacroPeriod(vcsel_period_pclks);

  return ((timeout_period_mclks * macro_period_ns) + (macro_period_ns / 2)) / 1000;
}
// Decode sequence step timeout in MCLKs from register value
// based on VL53L0X_decode_timeout()
// Note: the original function returned a unsigned  long, but the return value is
// always stored in a unsigned  int.
unsigned  int VL53L0X_decodeTimeout(unsigned  int reg_val)
{
  // format: "(LSByte * 2^MSByte) + 1"
  return (unsigned  int)((reg_val & 0x00FF) <<
         (unsigned  int)((reg_val & 0xFF00) >> 8)) + 1;
}

// Get sequence step timeouts
// based on get_sequence_step_timeout(),
// but gets all timeouts instead of just the requested one, and also stores
// intermediate values
void VL53L0X_getSequenceStepTimeouts(struct SequenceStepEnables const * enables, struct SequenceStepTimeouts * timeouts)
{
  timeouts->pre_range_vcsel_period_pclks = VL53L0X_getVcselPulsePeriod(VcselPeriodPreRange);

  timeouts->msrc_dss_tcc_mclks = VL53L0X_Read(MSRC_CONFIG_TIMEOUT_MACROP) + 1;
  timeouts->msrc_dss_tcc_us =
    VL53L0X_timeoutMclksToMicroseconds(timeouts->msrc_dss_tcc_mclks,
                               (unsigned char)timeouts->pre_range_vcsel_period_pclks);

  timeouts->pre_range_mclks =
    VL53L0X_decodeTimeout(VL53L0X_Read16Bit(PRE_RANGE_CONFIG_TIMEOUT_MACROP_HI));
  timeouts->pre_range_us =
    VL53L0X_timeoutMclksToMicroseconds(timeouts->pre_range_mclks,
      (unsigned char)timeouts->pre_range_vcsel_period_pclks);

  timeouts->final_range_vcsel_period_pclks = VL53L0X_getVcselPulsePeriod(VcselPeriodFinalRange);

  timeouts->final_range_mclks =
    VL53L0X_decodeTimeout(VL53L0X_Read16Bit(FINAL_RANGE_CONFIG_TIMEOUT_MACROP_HI));

  if (enables->pre_range)
  {
    timeouts->final_range_mclks -= timeouts->pre_range_mclks;
  }

  timeouts->final_range_us =
    VL53L0X_timeoutMclksToMicroseconds(timeouts->final_range_mclks,
      (unsigned char)timeouts->final_range_vcsel_period_pclks);
}

// Get the measurement timing budget in microseconds
// based on VL53L0X_get_measurement_timing_budget_micro_seconds()
// in us
unsigned  long VL53L0X_getMeasurementTimingBudget(void)
{
  struct SequenceStepEnables enables;
  struct SequenceStepTimeouts timeouts;

  unsigned  int const StartOverhead     = 1910; // note that this is different than the value in set_
  unsigned  int const EndOverhead        = 960;
  unsigned  int const MsrcOverhead       = 660;
  unsigned  int const TccOverhead        = 590;
  unsigned  int const DssOverhead        = 690;
  unsigned  int const PreRangeOverhead   = 660;
  unsigned  int const FinalRangeOverhead = 550;

  // "Start and end overhead times always present"
  unsigned  long budget_us = StartOverhead + EndOverhead;

  VL53L0X_getSequenceStepEnables(&enables);
  VL53L0X_getSequenceStepTimeouts(&enables, &timeouts);

  if (enables.tcc)
  {
    budget_us += (timeouts.msrc_dss_tcc_us + TccOverhead);
  }

  if (enables.dss)
  {
    budget_us += 2 * (timeouts.msrc_dss_tcc_us + DssOverhead);
  }
  else if (enables.msrc)
  {
    budget_us += (timeouts.msrc_dss_tcc_us + MsrcOverhead);
  }

  if (enables.pre_range)
  {
    budget_us += (timeouts.pre_range_us + PreRangeOverhead);
  }

  if (enables.final_range)
  {
    budget_us += (timeouts.final_range_us + FinalRangeOverhead);
  }

  measurement_timing_budget_us = budget_us; // store for internal reuse
  return budget_us;
}

// Convert sequence step timeout from microseconds to MCLKs with given VCSEL period in PCLKs
// based on VL53L0X_calc_timeout_mclks()
unsigned  long VL53L0X_timeoutMicrosecondsToMclks(unsigned  long timeout_period_us, unsigned  char vcsel_period_pclks)
{
  unsigned  long macro_period_ns = calcMacroPeriod(vcsel_period_pclks);

  return (((timeout_period_us * 1000) + (macro_period_ns / 2)) / macro_period_ns);
}


// Encode sequence step timeout register value from timeout in MCLKs
// based on VL53L0X_encode_timeout()
// Note: the original function took a unsigned  int, but the argument passed to it
// is always a unsigned  int.
unsigned  int VL53L0X_encodeTimeout(unsigned  int timeout_mclks)
{
  // format: "(LSByte * 2^MSByte) + 1"

  unsigned  long ls_byte = 0;
  unsigned  int ms_byte = 0;

  if (timeout_mclks > 0)
  {
    ls_byte = timeout_mclks - 1;

    while ((ls_byte & 0xFFFFFF00) > 0)
    {
      ls_byte >>= 1;
      ms_byte++;
    }

    return (ms_byte << 8) | (ls_byte & 0xFF);
  }
  else { return 0; }
}


bit VL53L0X_setMeasurementTimingBudget(unsigned  long budget_us)
{
  struct SequenceStepEnables enables;
  struct SequenceStepTimeouts timeouts;

  unsigned  int const StartOverhead      = 1320; // note that this is different than the value in get_
  unsigned  int const EndOverhead        = 960;
  unsigned  int const MsrcOverhead       = 660;
  unsigned  int const TccOverhead        = 590;
  unsigned  int const DssOverhead        = 690;
  unsigned  int const PreRangeOverhead   = 660;
  unsigned  int const FinalRangeOverhead = 550;

  unsigned  long const MinTimingBudget = 20000;
	unsigned  long used_budget_us;
	unsigned  long final_range_timeout_us;
  unsigned  int final_range_timeout_mclks;

  if (budget_us < MinTimingBudget) { return 0; }

  used_budget_us = StartOverhead + EndOverhead;

  VL53L0X_getSequenceStepEnables(&enables);
  VL53L0X_getSequenceStepTimeouts(&enables, &timeouts);

  if (enables.tcc)
  {
    used_budget_us += (timeouts.msrc_dss_tcc_us + TccOverhead);
  }

  if (enables.dss)
  {
    used_budget_us += 2 * (timeouts.msrc_dss_tcc_us + DssOverhead);
  }
  else if (enables.msrc)
  {
    used_budget_us += (timeouts.msrc_dss_tcc_us + MsrcOverhead);
  }

  if (enables.pre_range)
  {
    used_budget_us += (timeouts.pre_range_us + PreRangeOverhead);
  }

  if (enables.final_range)
  {
    used_budget_us += FinalRangeOverhead;

    // "Note that the final range timeout is determined by the timing
    // budget and the sum of all other timeouts within the sequence.
    // If there is no room for the final range timeout, then an error
    // will be set. Otherwise the remaining time will be applied to
    // the final range."

    if (used_budget_us > budget_us)
    {
      // "Requested timeout too big."
      return 0;
    }

    final_range_timeout_us = budget_us - used_budget_us;

    // set_sequence_step_timeout() begin
    // (SequenceStepId == VL53L0X_SEQUENCESTEP_FINAL_RANGE)

    // "For the final range timeout, the pre-range timeout
    //  must be added. To do this both final and pre-range
    //  timeouts must be expressed in macro periods MClks
    //  because they have different vcsel periods."

    final_range_timeout_mclks =
      VL53L0X_timeoutMicrosecondsToMclks(final_range_timeout_us,
                                 (unsigned char)timeouts.final_range_vcsel_period_pclks);

    if (enables.pre_range)
    {
      final_range_timeout_mclks += timeouts.pre_range_mclks;
    }

    VL53L0X_Write16Bit(FINAL_RANGE_CONFIG_TIMEOUT_MACROP_HI,
      VL53L0X_encodeTimeout(final_range_timeout_mclks));

    // set_sequence_step_timeout() end

    measurement_timing_budget_us = budget_us; // store for internal reuse
  }
  return 1;
}

// based on VL53L0X_perform_single_ref_calibration()
bit VL53L0X_performSingleRefCalibration(unsigned  char vhv_init_byte)
{
  VL53L0X_Write(SYSRANGE_START, 0x01 | vhv_init_byte); // VL53L0X_REG_SYSRANGE_MODE_START_STOP


  Delay100ms();
  if ((VL53L0X_Read(RESULT_INTERRUPT_STATUS) & 0x07) == 0)
  {
      return 0;
  }
  

  VL53L0X_Write(SYSTEM_INTERRUPT_CLEAR, 0x01);

  VL53L0X_Write(SYSRANGE_START, 0x00);

  return 1;
}





// Returns a range reading in millimeters when continuous mode is active
// (readRangeSingleMillimeters() also calls this function after starting a
// single-shot range measurement)
unsigned  int VL53L0X_readRangeContinuousMillimeters(void)
{
	unsigned  int range;
	
  // startTimeout();

  if ((VL53L0X_Read(RESULT_INTERRUPT_STATUS) & 0x07) == 0)
  {
    return -1;
  }
	
  // assumptions: Linearity Corrective Gain is 1000 (default);
  // fractional ranging is not enabled
  range = VL53L0X_Read16Bit(RESULT_RANGE_STATUS + 10);

  VL53L0X_Write(SYSTEM_INTERRUPT_CLEAR, 0x01);

  return range;
}


// Performs a single-shot range measurement and returns the reading in
// millimeters
// based on VL53L0X_PerformSingleRangingMeasurement()
unsigned  int VL53L0X_readRangeSingleMillimeters(void)
{
  long i=0;
  VL53L0X_Write(0x80, 0x01);
  VL53L0X_Write(0xFF, 0x01);
  VL53L0X_Write(0x00, 0x00);
  VL53L0X_Write(0x91, stop_variable);
  VL53L0X_Write(0x00, 0x01);
  VL53L0X_Write(0xFF, 0x00);
  VL53L0X_Write(0x80, 0x00);

  VL53L0X_Write(SYSRANGE_START, 0x01);

  // "Wait until start bit has been cleared"
  // startTimeout();

  if(VL53L0X_Read(SYSRANGE_START) & 0x01)
  {
    return  -1;
  }
  return VL53L0X_readRangeContinuousMillimeters();
}
// void VL53L0X_startread()
// {
//   VL53L0X_Write(0x80, 0x01);
//   VL53L0X_Write(0xFF, 0x01);
//   VL53L0X_Write(0x00, 0x00);
//   VL53L0X_Write(0x91, stop_variable);
//   VL53L0X_Write(0x00, 0x01);
//   VL53L0X_Write(0xFF, 0x00);
//   VL53L0X_Write(0x80, 0x00);

//   VL53L0X_Write(SYSRANGE_START, 0x01);
// }
// void VL53L0X_readdata()
// {
//   if ((VL53L0X_Read(SYSRANGE_START) & 0x01)==0)
//   {
    
//   }
  
// }

void VL53L0_init()
{
	unsigned  char spad_count;
	unsigned  char spad_type_is_aperture;
	unsigned  char ref_spad_map[6];
	unsigned  char first_spad_to_enable;
	unsigned  char spads_enabled;
	unsigned  char i;
	P1_MODE_IO_PU(GPIO_Pin_4|GPIO_Pin_5);

	 // sensor uses 1V8 mode for I/O by default; switch to 2V8 mode if necessary
	//  VL53L0X_Write(VHV_CONFIG_PAD_SCL_SDA__EXTSUP_HV,VL53L0X_Read(VHV_CONFIG_PAD_SCL_SDA__EXTSUP_HV) | 0x01); // set bit 0
	VL53L0X_Write(0x88, 0x00);

	VL53L0X_Write(0x80, 0x01);
	VL53L0X_Write(0xFF, 0x01);
	VL53L0X_Write(0x00, 0x00);
	stop_variable = VL53L0X_Read(0x91);
	VL53L0X_Write(0x00, 0x01);
	VL53L0X_Write(0xFF, 0x00);
	VL53L0X_Write(0x80, 0x00);

	  // disable SIGNAL_RATE_MSRC (bit 1) and SIGNAL_RATE_PRE_RANGE (bit 4) limit checks
	VL53L0X_Write(MSRC_CONFIG_CONTROL, VL53L0X_Read(MSRC_CONFIG_CONTROL) | 0x12);

	    // set final range signal rate limit to 0.25 MCPS (million counts per second)
    VL53L0X_setSignalRateLimit(0.25);

	VL53L0X_Write(SYSTEM_SEQUENCE_CONFIG, 0xFF);

	if (!VL53L0X_getSpadInfo(&spad_count, &spad_type_is_aperture)) { return ; }

  // The SPAD map (RefGoodSpadMap) is read by VL53L0X_get_info_from_device() in
  // the API, but the same data seems to be more easily readable from
  // GLOBAL_CONFIG_SPAD_ENABLES_REF_0 through _6, so read it from there
  VL53L0X_ReadMulti(GLOBAL_CONFIG_SPAD_ENABLES_REF_0, ref_spad_map, 6);

  VL53L0X_Write(0xFF, 0x01);
  VL53L0X_Write(DYNAMIC_SPAD_REF_EN_START_OFFSET, 0x00);
  VL53L0X_Write(DYNAMIC_SPAD_NUM_REQUESTED_REF_SPAD, 0x2C);
  VL53L0X_Write(0xFF, 0x00);
  VL53L0X_Write(GLOBAL_CONFIG_REF_EN_START_SELECT, 0xB4);

  
  VL53L0X_Write(0xFF, 0x01);
  VL53L0X_Write(DYNAMIC_SPAD_REF_EN_START_OFFSET, 0x00);
  VL53L0X_Write(DYNAMIC_SPAD_NUM_REQUESTED_REF_SPAD, 0x2C);
  VL53L0X_Write(0xFF, 0x00);
  VL53L0X_Write(GLOBAL_CONFIG_REF_EN_START_SELECT, 0xB4);

  first_spad_to_enable = spad_type_is_aperture ? 12 : 0; // 12 is the first aperture spad
  spads_enabled = 0;

  for (i = 0; i < 48; i++)
  {
    if (i < first_spad_to_enable || spads_enabled == spad_count)
    {
      // This bit is lower than the first one that should be enabled, or
      // (reference_spad_count) bits have already been enabled, so zero this bit
      ref_spad_map[i / 8] &= ~(1 << (i % 8));
    }
    else if ((ref_spad_map[i / 8] >> (i % 8)) & 0x1)
    {
      spads_enabled++;
    }
  }
  VL53L0X_WriteMulti(GLOBAL_CONFIG_SPAD_ENABLES_REF_0, ref_spad_map, 6);

  
  VL53L0X_Write(0xFF, 0x01);
  VL53L0X_Write(0x00, 0x00);

  VL53L0X_Write(0xFF, 0x00);
  VL53L0X_Write(0x09, 0x00);
  VL53L0X_Write(0x10, 0x00);
  VL53L0X_Write(0x11, 0x00);

  VL53L0X_Write(0x24, 0x01);
  VL53L0X_Write(0x25, 0xFF);
  VL53L0X_Write(0x75, 0x00);

  VL53L0X_Write(0xFF, 0x01);
  VL53L0X_Write(0x4E, 0x2C);
  VL53L0X_Write(0x48, 0x00);
  VL53L0X_Write(0x30, 0x20);

  VL53L0X_Write(0xFF, 0x00);
  VL53L0X_Write(0x30, 0x09);
  VL53L0X_Write(0x54, 0x00);
  VL53L0X_Write(0x31, 0x04);
  VL53L0X_Write(0x32, 0x03);
  VL53L0X_Write(0x40, 0x83);
  VL53L0X_Write(0x46, 0x25);
  VL53L0X_Write(0x60, 0x00);
  VL53L0X_Write(0x27, 0x00);
  VL53L0X_Write(0x50, 0x06);
  VL53L0X_Write(0x51, 0x00);
  VL53L0X_Write(0x52, 0x96);
  VL53L0X_Write(0x56, 0x08);
  VL53L0X_Write(0x57, 0x30);
  VL53L0X_Write(0x61, 0x00);
  VL53L0X_Write(0x62, 0x00);
  VL53L0X_Write(0x64, 0x00);
  VL53L0X_Write(0x65, 0x00);
  VL53L0X_Write(0x66, 0xA0);

  VL53L0X_Write(0xFF, 0x01);
  VL53L0X_Write(0x22, 0x32);
  VL53L0X_Write(0x47, 0x14);
  VL53L0X_Write(0x49, 0xFF);
  VL53L0X_Write(0x4A, 0x00);

  VL53L0X_Write(0xFF, 0x00);
  VL53L0X_Write(0x7A, 0x0A);
  VL53L0X_Write(0x7B, 0x00);
  VL53L0X_Write(0x78, 0x21);

  VL53L0X_Write(0xFF, 0x01);
  VL53L0X_Write(0x23, 0x34);
  VL53L0X_Write(0x42, 0x00);
  VL53L0X_Write(0x44, 0xFF);
  VL53L0X_Write(0x45, 0x26);
  VL53L0X_Write(0x46, 0x05);
  VL53L0X_Write(0x40, 0x40);
  VL53L0X_Write(0x0E, 0x06);
  VL53L0X_Write(0x20, 0x1A);
  VL53L0X_Write(0x43, 0x40);

  VL53L0X_Write(0xFF, 0x00);
  VL53L0X_Write(0x34, 0x03);
  VL53L0X_Write(0x35, 0x44);

  VL53L0X_Write(0xFF, 0x01);
  VL53L0X_Write(0x31, 0x04);
  VL53L0X_Write(0x4B, 0x09);
  VL53L0X_Write(0x4C, 0x05);
  VL53L0X_Write(0x4D, 0x04);

  VL53L0X_Write(0xFF, 0x00);
  VL53L0X_Write(0x44, 0x00);
  VL53L0X_Write(0x45, 0x20);
  VL53L0X_Write(0x47, 0x08);
  VL53L0X_Write(0x48, 0x28);
  VL53L0X_Write(0x67, 0x00);
  VL53L0X_Write(0x70, 0x04);
  VL53L0X_Write(0x71, 0x01);
  VL53L0X_Write(0x72, 0xFE);
  VL53L0X_Write(0x76, 0x00);
  VL53L0X_Write(0x77, 0x00);

  VL53L0X_Write(0xFF, 0x01);
  VL53L0X_Write(0x0D, 0x01);

  VL53L0X_Write(0xFF, 0x00);
  VL53L0X_Write(0x80, 0x01);
  VL53L0X_Write(0x01, 0xF8);

  VL53L0X_Write(0xFF, 0x01);
  VL53L0X_Write(0x8E, 0x01);
  VL53L0X_Write(0x00, 0x01);
  VL53L0X_Write(0xFF, 0x00);
  VL53L0X_Write(0x80, 0x00);

  
  VL53L0X_Write(SYSTEM_INTERRUPT_CONFIG_GPIO, 0x04);
  VL53L0X_Write(GPIO_HV_MUX_ACTIVE_HIGH, VL53L0X_Read(GPIO_HV_MUX_ACTIVE_HIGH) & ~0x10); // active low
  VL53L0X_Write(SYSTEM_INTERRUPT_CLEAR, 0x01);

  measurement_timing_budget_us = VL53L0X_getMeasurementTimingBudget();

  // "Disable MSRC and TCC by default"
  // MSRC = Minimum Signal Rate Check
  // TCC = Target CentreCheck
  // -- VL53L0X_SetSequenceStepEnable() begin

  VL53L0X_Write(SYSTEM_SEQUENCE_CONFIG, 0xE8);

  // -- VL53L0X_SetSequenceStepEnable() end

  // "Recalculate timing budget"
  VL53L0X_setMeasurementTimingBudget(measurement_timing_budget_us);

  // VL53L0X_StaticInit() end

  // VL53L0X_PerformRefCalibration() begin (VL53L0X_perform_ref_calibration())

  // -- VL53L0X_perform_vhv_calibration() begin

  VL53L0X_Write(SYSTEM_SEQUENCE_CONFIG, 0x01);
  if (!VL53L0X_performSingleRefCalibration(0x40)) { return ; }

  // -- VL53L0X_perform_vhv_calibration() end

  // -- VL53L0X_perform_phase_calibration() begin

  VL53L0X_Write(SYSTEM_SEQUENCE_CONFIG, 0x02);
  if (!VL53L0X_performSingleRefCalibration(0x00)) { return ; }

  // -- VL53L0X_perform_phase_calibration() end

  // "restore the previous Sequence Config"
  VL53L0X_Write(SYSTEM_SEQUENCE_CONFIG, 0xE8);

  // VL53L0X_PerformRefCalibration() end

    // lower the return signal rate limit (default is 0.25 MCPS)
  // VL53L0X_setSignalRateLimit(0.1);

  return ;
}


